using UnityEngine;
using System.Collections;

public class DBUtils
{
	public static string Md5Sum(string strToEncrypt)
	{
	    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
	    byte[] bytes = ue.GetBytes(strToEncrypt);
	
	    // encrypt bytes
	    System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
	    byte[] hashBytes = md5.ComputeHash(bytes);
	
	    // Convert the encrypted bytes back to a string (base 16)
	    string hashString = "";
		
	    for (int i = 0; i < hashBytes.Length; i++)
	    {
	        hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
	    }
	
	    return hashString.PadLeft(32, '0');
	}
	
	public static IEnumerator PostScore(string name, int level, int score)
	{
		string secretKey = "quesserquiss___pass";
		string hash = Md5Sum(name + level.ToString() + score.ToString() + secretKey);
		
		string url = "http://z3dgames.com/HTMLtest/AddScore.php?"
				   + "name=" + WWW.EscapeURL(name) 
				   + "&level=" + level.ToString() 
				   + "&score=" + score 
				   + "&hash=" + hash;
		
		Debug.Log(url);
		
		WWW post = new WWW(url);
		
		yield return post;
		
		Debug.Log(post.text);
		
		if(post.error != null)
			Debug.LogError("There was an error: " + post.error);
		
	}
	
	public delegate void GetScoreCallback(string leaderboard);
	public static IEnumerator GetScore(GetScoreCallback callback)
	{
		WWW scores = new WWW("http://z3dgames.com/HTMLtest/GetScore.php");
		
		Debug.Log(scores);
		
		yield return scores;
		
		if(scores.error != null)
		{
			Debug.LogError("There was an error: " + scores.error);
		}
		
		callback(scores.text);
	}
}
